package com.hp.bon.sgw.core.processor;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.service.SGWDataStoreService;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.util.dcc.DccAvpHelper;
import com.hp.ocs.diameter.message.Message;
import java.util.List;
import org.slf4j.Logger;

public class ActiveProcessor extends Processor
{
  private volatile int sendedSRCount;
  private volatile int failedCount;
  private volatile int runingStatus = 0;

  public int process(CallParam callParam)
  {
    return 0;
  }

  public void resetReqSendCount(int sendCount)
  {
    this.runingStatus = 0;
    this.failedCount = 0;
    this.sendedSRCount = sendCount;
  }

  public int getResultStatus()
  {
    return this.runingStatus;
  }

  public int endProcess(CallParam callParam)
  {
    if (callParam.getRecvResponse() != null) {
      StringBuilder sb = new StringBuilder();
      Message cca = (Message)callParam.getRecvResponse();
      int serviceResultCode = DccAvpHelper.getCCAMessageServiceResultCode(cca);
      sb.append("received successful " + callParam.getServiceContextId() + " cca ,service result code :" + serviceResultCode);
      Constants.LOG.info(sb.toString());

      if (serviceResultCode == 0) {
        this.runingStatus = 1;
        Message req = (Message)callParam.getRequest();
        boolean isActive = false;
        if (callParam.getServiceContextId().startsWith("Active.")) {
          isActive = true;
        }
        Object object = req.getStateObject();
        if (object != null) {
          List<Integer> list = (List)object;
          String hql = "update SGWCapabilityProvided set status = " + (isActive ? 1 : 0) + " ,statusTime = sysdate where id = ";
          for (Integer id : list) {
            SpringContext.getInstance().getDataStoreService().addHSQL(hql + id, true);
          }
        }
        else if (!isActive) {
          String hql = "update SGWCapabilityProvided set status = 0 ,statusTime = sysdate";
          SpringContext.getInstance().getDataStoreService().addHSQL(hql, true);
        }
      }
      else {
        this.failedCount += 1;
        if (this.failedCount == this.sendedSRCount) {
          this.runingStatus = -1;
          Constants.LOG.warn("all sr answer capability active/deactive failed ");
        }
      }
    } else {
      this.runingStatus = -2;
    }
    return 0;
  }
}